<template>
  <div>
    <!-- 表单区域 -->
    <el-form :inline="true" :model="query" ref="queryRef">
      <el-form-item prop="name">
        <el-input v-model="query.name" placeholder="商品名称"></el-input>
      </el-form-item>
      <el-form-item prop="code" >
        <el-input v-model="query.code" placeholder="商品编码"></el-input>
      </el-form-item>
      <el-form-item prop="supplierName">
        <el-input v-model="query.supplierName"
        @click.native="chooseSupplierDialogVisible = true"
        placeholder="请选择供应商" readonly ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData">查询</el-button>
        <el-button type="primary" @click="resetForm">重置</el-button>
        <el-button type="primary" @click="addGoods">新增</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格区域 -->
    <el-table :data="goodsList" style="width: 100%" border stripe >
      <el-table-column type="index" label="*"></el-table-column>
      <el-table-column prop="name" label="商品名称"></el-table-column>
      <el-table-column prop="code" label="商品编码"></el-table-column>
      <el-table-column prop="spec" label="商品规格"></el-table-column>
      <el-table-column prop="retailPrice" label="零售价"></el-table-column>
      <el-table-column prop="purchasePrice" label="进货价"></el-table-column>
      <el-table-column prop="storageNum" label="库存数量"></el-table-column>
      <el-table-column prop="supplierName" label="供应商"></el-table-column>
      <el-table-column label="操作" width="180px">
        <template slot-scope="scope">
            <el-button size="mini" @click="updateGoods(scope.row.id)">编辑</el-button>
            <el-button  size="mini" type="danger" @click="deleteGoods(scope.row.id)">删除</el-button>
         </template>
      </el-table-column>
    </el-table>
        <!-- 分页区域 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
<!-- 选择供应商的对话框 -->
    <el-dialog title="选择供应商" @close="chooseSupplierClosed" :visible.sync="chooseSupplierDialogVisible"
        width="50%">
        <supplier :isDialog="true" @chooseRow="chooseRow"></supplier>
    </el-dialog>
    <!-- 新增商品的对话框 -->
    <el-dialog @close="addGoodsClosed"
      :title="chooseTitle + '商品'" :visible.sync="addGoodsDialogVisible"
      width="50%">
        <el-form :rules="addGoodsFormRules" :model="addGoodsForm" ref="addGoodsFormRef" label-width="90px">
          <el-form-item prop="name" label="商品名称">
            <el-input v-model="addGoodsForm.name" placeholder="商品名称"></el-input>
          </el-form-item>
          <el-form-item prop="code" label="商品编码" >
            <el-input v-model="addGoodsForm.code" placeholder="商品编码"></el-input>
          </el-form-item>
          <el-form-item prop="spec" label="商品规格">
            <el-input v-model="addGoodsForm.spec" placeholder="商品规格"></el-input>
          </el-form-item>
          <el-form-item prop="retailPrice" label="零售价">
            <el-input v-model="addGoodsForm.retailPrice" placeholder="零售价"></el-input>
          </el-form-item>
          <el-form-item prop="purchasePrice" label="进货价">
            <el-input v-model="addGoodsForm.purchasePrice" placeholder="进货价"></el-input>
          </el-form-item>
          <el-form-item prop="storageNum" label="库存数量">
            <el-input v-model="addGoodsForm.storageNum" placeholder="库存数量"></el-input>
          </el-form-item>
          <el-form-item prop="supplierName" label="供应商">
            <el-input v-model="addGoodsForm.supplierName"
            @click.native="addChooseSupplier"
            placeholder="请选择供应商" readonly ></el-input>
          </el-form-item>
        </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addGoodsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addGoodsForm.id === null ? submitAddGoods('addGoodsFormRef') : submitUpdateGoods('addGoodsFormRef')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import goodsApi from '../../api/goods'
import Supplier from '../supplier/Supplier'
export default {
  components: {
    Supplier
  },
  computed: {
    chooseTitle () {
      if (this.addGoodsForm.id === null) {
        return '新增'
      } else {
        return '编辑'
      }
    }
  },
  data () {
    return {
      // 商品列表数据
      goodsList: [],
      currentPage: 1,
      pageSize: 1,
      query: {
        name: '',
        code: '',
        supplierName: ''
      },
      total: 0,
      // 控制供应商对话框的显示和隐藏
      chooseSupplierDialogVisible: false,
      // 新增商品对话框的关闭和显示
      addGoodsDialogVisible: false,
      addGoodsFormRules: {
        name: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '商品编码不能为空', trigger: 'blur' }
        ],
        retailPrice: [
          { required: true, message: '零售价不能为空', trigger: 'blur' }
        ]
      },
      addGoodsForm: {
        id: null,
        name: '',
        code: '',
        spec: '',
        purchasePrice: 0,
        retailPrice: 0,
        storageNum: 0,
        supplierName: ''
      },
      // 判断到底是表单头上面的选择供应商还是新增里面的选择供应商
      isAdd: false
    }
  },
  created () {
    this.fetchData()
  },
  methods: {
    // 获取商品列表数据
    fetchData () {
      goodsApi.getGoodsList(this.currentPage, this.pageSize, this.query).then(response => {
        const resp = response.data
        console.log(resp)
        if (resp.flag) {
          this.total = resp.data.total
          this.goodsList = resp.data.rows
        } else {
          this.$message.error('获取商品数据失败')
        }
      })
    },
    // 编辑按钮
    updateGoods (rowId) {
      console.log(rowId)
      // 首先清空数据
      this.addGoods()
      // 将数据映射到表单中
      goodsApi.getById(rowId).then(response => {
        const res = response.data
        // console.log(res)
        if (res.flag) {
          this.addGoodsForm = res.data
          console.log(this.addGoodsForm)
        }
      })
    },
    // 删除按钮
    deleteGoods (rowId) {
      console.log(rowId)
      this.$confirm('确认删除这条记录么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认
        goodsApi.deleteById(rowId).then(response => {
          const res = response.data
          if (res.flag) {
            this.$message.success(res.message)
            this.fetchData()
          } else {
            this.$message.error('删除失败')
          }
        })
      }).catch(error => {
        this.$message.info('已取消删除')
        return error
      })
    },
    // 新增按钮
    addGoods () {
      this.addGoodsDialogVisible = true
      // 这里必须这样处理，添加表单打印出来的才有数值
      this.$nextTick(() => {
        this.$refs.addGoodsFormRef.resetFields()
        // 这一步一定要有，区别修改和新增的关键
        this.addGoodsForm.id = null
      })
    },
    // 监听新增对话框的关闭，清空
    // 这样处置的话,对话框一关闭，表单数据就没了，262行打印出来的是个空的
    addGoodsClosed () {
      // this.$nextTick(() => {
      //   this.$refs.addGoodsFormRef.resetFields()
      // })
    },
    // 重置按钮
    resetForm () {
      this.$refs.queryRef.resetFields()
      // 还要重置选择供应商里面的高亮
      // this.query.supplierName = ''
    },
    // 监听对话框的关闭，清空高亮数据
    chooseSupplierClosed () {
    },
    // 子组件传递过来的数据
    chooseRow (currentRow) {
      console.log(currentRow)
      if (this.isAdd) {
        // 如果此时新增窗口
        this.addGoodsForm.supplierName = currentRow.name
      } else {
        this.query.supplierName = currentRow.name
      }
      // 用完之后记得回归原来的
      this.isAdd = false
      this.chooseSupplierDialogVisible = false
    },
    // 分页
    handleSizeChange (newSize) {
      this.pageSize = newSize
      this.fetchData()
    },
    handleCurrentChange (newPage) {
      this.currentPage = newPage
      this.fetchData()
    },
    // 判断选择供应商是谁调用的
    addChooseSupplier () {
      this.isAdd = true
      this.chooseSupplierDialogVisible = true
    },
    // 点击提交按钮，新增商品
    submitAddGoods (formNameRef) {
      this.$refs[formNameRef].validate(valid => {
        if (valid) {
          console.log(valid)
          console.log(this.addGoodsForm)
          goodsApi.addGoods(this.addGoodsForm).then(response => {
            const resp = response.data
            console.log(resp)
            if (resp.flag) {
              this.$message.success('新增成功')
              this.fetchData()
              this.addGoodsDialogVisible = false
            } else {
              this.$message.error('新增失败')
            }
          })
        } else {
          return false
        }
      })
    },
    // 点击修改供应商窗口的确定按钮
    submitUpdateGoods (formNameRef) {
      this.$refs[formNameRef].validate(valid => {
        if (valid) {
          console.log(this.addGoodsForm)
          goodsApi.update(this.addGoodsForm).then(response => {
            const res = response.data
            console.log(res)
            if (res.flag) {
              this.$message.success(res.message)
              console.log(2)
              this.fetchData()
              this.addGoodsDialogVisible = false
              console.log(3)
            } else {
              this.$message({
                type: 'warning',
                message: '修改失败'
              })
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style scoped>
.el-form{
  margin-top: 15px
}
.el-table{
  margin-top: 15px
}
</style>
